<?php


namespace app\controller;


use app\model\Images;
use app\model\Answer as AnswerModel;
use app\model\Questions;
use app\validate\Image;
use Lizhichao\Word\VicWord;
use think\facade\Session;
use think\Request;

class Answer extends Base
{
    public function submit(Request $request){
        $data=$request->param();
        $files = request()->file('image');
        $username=Session::get('username');
        $user=\app\model\User::where('userName',$username)->find();
        $question=Questions::where('q_id',$data['q_id'])->find();
            $answer=AnswerModel::create([
                'a_user'=>$username,
                'q_id'=>$data['q_id'],
                'a_content'=>$data['a_content'],
                'q_user'=>$question->q_user,
                'user_head'=>$user->userImage
            ])->toArray();
            $a_id=$answer['id'];
                if($files){
                    try {
                        validate(Image::class)
                            ->check($files);
                        $savename = [];
                        foreach($files as $file) {
                            $save = \think\facade\Filesystem::disk('public')->putFile( 'answers', $file);
                            $image=Images::create([
                                'is_answ'=>1,
                                'a_id'=>$a_id,
                                'img_add'=>'storage/'.str_replace('\\','/',$save)
                            ]);
                            $savename[]=$save;
                        }
                        $answer['images']=$savename;

                    } catch (\think\exception\ValidateException $e) {
                        return $this->createApi([],$e->getMessage(),400);
                    }
                }
        return $this->createApi($answer,'回答保存成功',200);
    }
    public function readAnswers(Request $request){
        $data=$request->param();
        if(isset($data['q_id'])&&$data['q_id']!=0){
            $answer=AnswerModel::where('q_id',$data['q_id'])->field('a_uname,a_content')->select()->toArray();
            $images=Images::where('a_id',$data['a_id'])->field('img_add')->select()->toArray();
            $ques['images']=$images;
            if($ques){
                return $this->createApi($answer,'查看回答成功',200);
            }else{
                return $this->createApi([],'查看回答失败',204);
            }
        }
    }
    public function read(Request $request){
        $data=$request->param();
        $answer=AnswerModel::where('a_id',$data['id'])->find()->toArray();
        $images=Images::where('a_id',$data['id'])->select()->toArray();
        $answer['images']=$images;
        return $this->createApi($answer,'success',200);
    }


}